package controllers

import (
	"disease/models"
	beego "github.com/beego/beego/v2/server/web"
)

type DiseaseController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *DiseaseController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var disease []models.Disease
	err := models.DB.Find(&disease).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据查询成功",
			Data: disease,
		}
		c.ServeJSON()
	}
}

func (c *DiseaseController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	name := c.GetString("name")
	tel := c.GetString("tel")
	register := c.GetString("register")
	price, _ := c.GetFloat("price")
	time := c.GetString("time")
	disease := models.Disease{
		Img:      "http://127.0.0.1:8080/" + path,
		Name:     name,
		Tel:      tel,
		Register: register,
		Price:    price,
		Time:     time,
	}

	err = models.DB.Create(&disease).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: disease,
		}
		c.ServeJSON()
	}

}
